import request from '@/utils/request'

const redingTimer = (config = {}) => {
	const {
		storageKey = 'readingRecords', // 本地存储键名
			maxDuration = 30, // 单次最大记录时长（秒）
			autoSave = true // 是否自动保存
	} = config;

	// 状态管理
	let timer = null;
	let startTimestamp = null;
	let currentId = null;

	// 工具方法：加载历史记录
	const loadRecords = () => {
		try {
			const records = uni.getStorageSync(storageKey);
			return records ? JSON.parse(records) : [];
		} catch (e) {
			console.error('读取记录失败:', e);
			return [];
		}
	};

	// 工具方法：保存记录
	const saveRecords = (records) => {
		try {
			uni.setStorageSync(storageKey, JSON.stringify(records));
		} catch (e) {
			console.error('保存记录失败:', e);
		}
	};

	// 时间格式化方法
	const formatDate = (timestamp) =>
		new Date(timestamp).toISOString().split('T')[0];

	const formatTime = (timestamp) =>
		new Date(timestamp).toTimeString().split(' ')[0].substring(0, 8);

	return {
		/**
		 * 开始计时
		 * @param {string} id - 内容唯一标识
		 */
		start(id) {
			if (timer) this.stop();

			currentId = id;
			startTimestamp = Date.now();

			timer = setInterval(() => {
				const duration = Math.floor((Date.now() - startTimestamp) / 1000);
				if (duration >= maxDuration) {
					this.stop();
				}
			}, 1000);
		},

		/**
		 * 停止计时并生成记录
		 * @returns {object} 本次阅读记录
		 */
		stop() {
			if (!timer) return null;

			clearInterval(timer);
			timer = null;

			const endTimestamp = Date.now();
			const rawDuration = Math.floor((endTimestamp - startTimestamp) / 1000);
			const duration = Math.min(rawDuration, maxDuration);

			const record = {
				id: currentId,
				duration,
				date: formatDate(startTimestamp),
				startTime: formatTime(startTimestamp),
				endTime: formatTime(endTimestamp)
			};

			if (autoSave) {
				const records = loadRecords();
				records.push(record);
				saveRecords(records);
			}

			currentId = null;
			startTimestamp = null;

			return record;
		},

		/**
		 * 获取历史记录
		 * @returns {array} 所有存储的记录
		 */
		getHistory() {
			return loadRecords();
		},

		/**
		 * 清空所有记录
		 */
		clearHistory() {
			saveRecords([]);
		},

		/**
		 * 发送数据（阅读时长）
		 */
		async sendData() {
			const record = loadRecords();
			const duration = record.reduce((sum, item) => sum + item.duration, 0) / 60;

			if (duration > 0.5) {
				await request({
					url: '/app/readingRecords/saveOrUpdate',
					method: 'POST',
					data: {
						contentId: record[0]?.id,
						contentType: storageKey,
						duration: Math.ceil(duration)
					}
				});
				await this.clearHistory();

			}
		},

		/**
		 * 发送数据(在线时长)
		 */
		async sendDataUserActive() {
			const record = loadRecords();
			const duration = record.reduce((sum, item) => sum + item.duration, 0) / 60;
			if (duration > 2) {
				await request({
					url: `/app/userActive/saveOrUpdate?duration=${Math.ceil(duration)}`,
					method: 'POST',
				});
				await this.clearHistory();
			}
		},
	};
};

export default redingTimer;